import { createStore, Store, useStore as useVuexStore } from 'vuex'
import { IRootStore, IStoreType } from './types'
import login from './login/login'
import system from './system/system'
import dashboard from './analysis/dashboard'
import { getPageListData } from '@/service/main/system/system'

const store = createStore<IRootStore>({
  state() {
    return {
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  mutations: {
    changeEntireDepartment(state, list) {
      state.entireDepartment = list
    },
    changeEntireRole(state, list) {
      state.entireRole = list
    },
    changeEntireMene(state, list) {
      state.entireMenu = list
    }
  },
  actions: {
    async getEtireDepartment({ commit }) {
      const departmentList = await getPageListData('department/list', {
        offset: 0,
        size: 1000
      })
      commit('changeEntireDepartment', departmentList.data.list)

      const roleList = await getPageListData('role/list', {
        offset: 0,
        size: 1000
      })
      commit('changeEntireRole', roleList.data.list)

      const menuResult = await getPageListData('menu/list', {})
      commit('changeEntireMene', menuResult.data.list)
    }
  },
  getters: {},
  modules: {
    login,
    system,
    dashboard
  }
})

export function setupStore(): void {
  store.dispatch('login/loadLocalLogin')
  // 此处在退出登录之后，重新登录的时候，有可能在请求的时候还没有获取到token，因为请求是异步的，所以最好把该请求放到获取token之后再调用
  // store.dispatch('getEtireDepartment')
}

export function useStore(): Store<IStoreType> {
  // 主动调用vuex自己的useStore
  return useVuexStore()
}

export default store
